package api

import (
	"counter-help/admin/server/global"
	"counter-help/admin/server/model/common/response"
	"counter-help/admin/server/model/customer"
	orderReq "counter-help/admin/server/model/order/request"
	"counter-help/admin/server/plugin/wxpay/model"
	"counter-help/admin/server/plugin/wxpay/service"
	"counter-help/admin/server/utils"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"math"
	"strconv"
	"time"
)

type WxpayApi struct{}

// @Tags Wxpay
// @Summary 获取微信支付二维码和ID
// @Produce  application/json
// @Success 200 {string} string "{"success":true,"data":{},"msg":"发送成功"}"
// @Router /wxpay/getPayCode[post]
func (p *WxpayApi) GetPayCode(c *gin.Context) {
	var order customer.CusOrder
	userID := utils.GetUserID(c)
	type WxPay struct {
		OrderId string `json:"order_id" binding:"required"` // 确保 JSON 中有 order_id 字段
	}
	var wxpay WxPay
	err := c.ShouldBindJSON(&wxpay)
	if err != nil {
		response.FailWithMessage("数据绑定失败", c)
		return
	}
	err = global.GVA_DB.Debug().Where("id = ? AND order_user_id = ?", wxpay.OrderId, userID).First(&order).Error
	if err != nil {
		response.FailWithMessage("获取订单失败", c)
		return
	}
	var scanOrder orderReq.ScanCode
	//if order.OrderNo == "" || !order.IsPaid {
	//	currentTime := time.Now()
	//
	//	// 打印当前时间
	//	fmt.Println("当前时间:", currentTime)
	//	// 获取年、月、日、时、分、秒
	//	year := currentTime.Year()
	//	month := currentTime.Month() // 返回 time.Month 类型
	//	day := currentTime.Day()
	//	// 使用当前时间作为随机数种子
	//	rand.Seed(time.Now().UnixNano())
	//	// 生成一个范围在 10 到 99 之间的随机数
	//	randomNumber := rand.Intn(90) + 10 // 90 是范围的大小，10 是最小值
	//	orderNo := fmt.Sprintf("SN%d%d%d%d%d", randomNumber, year, month, day, order.ID)
	//	scanOrder.OrderNo = orderNo
	//} else {
	//	scanOrder.OrderNo = order.OrderNo
	//}
	// 获取当前微秒时间戳（Go 1.17+）
	microseconds := time.Now().UnixMicro()
	// 正确转换为十进制字符串
	timestampStr := strconv.FormatInt(microseconds, 10)
	scanOrder.OrderNo = wxpay.OrderId + "_" + timestampStr
	scanOrder.Name = order.Title
	scanOrder.OrderId = wxpay.OrderId
	if order.ExPrice == nil {
		response.FailWithMessage("订单价格无效", c)
		return
	}
	//updateData := map[string]interface{}{
	//	"order_no": scanOrder.OrderNo, // 设置要更新的字段
	//}
	//// 使用 Debug() 方法查看生成的 SQL 语句
	//result := global.GVA_DB.Debug().Model(&order).Where("id = ? AND order_user_id = ?", wxpay.OrderId, userID).Updates(updateData)
	//
	//// 检查更新结果
	//if result.Error != nil {
	//	response.FailWithMessage("获取付款码失败:"+err.Error(), c)
	//	return
	//}
	price := *order.ExPrice * 100
	scanOrder.Amount = int(math.Round(price)) // 使用 math.Round 进行四舍五入
	if err, codeUrl, codeId := service.ServiceGroupApp.GetPayCode(scanOrder); err != nil {
		global.GVA_LOG.Error("失败!", zap.Error(err))
		response.FailWithMessage("获取付款码失败:"+err.Error(), c)
	} else {
		if codeId == "" {
			codeId = scanOrder.OrderNo
		}
		response.OkWithData(gin.H{
			"codeUrl": codeUrl,
			"codeId":  codeId,
		}, c)
	}
}

// @Tags Wxpay
// @Summary 获取支付结果
// @Produce  application/json
// @Success 200 {string} string "{"success":true,"data":{},"msg":"发送成功"}"
// @Router /wxpay/getOrderById[get]
func (p *WxpayApi) GetOrderById(c *gin.Context) {
	id := c.Query("orderID")
	fmt.Println("ID:::::", id)
	if err, data := service.ServiceGroupApp.GetOrderById(id); err != nil {
		global.GVA_LOG.Error("失败!", zap.Error(err))
		response.FailWithMessage("获取付款码失败:"+err.Error(), c)
	} else {
		response.OkWithData(data, c)
	}
}

// @Tags Wxpay
// @Summary 获取支付结果
// @Produce  application/json
// @Success 200 {string} string "{"success":true,"data":{},"msg":"发送成功"}"
// @Router /wxpay/payAction[post]
func (p *WxpayApi) PayAction(c *gin.Context) {
	var pay model.PayAction
	c.ShouldBindJSON(&pay)
	if err := service.ServiceGroupApp.PayAction(pay); err != nil {
		global.GVA_LOG.Error("失败!", zap.Error(err))
		c.JSON(200, gin.H{
			"code":    "FAIL",
			"message": "失败",
		})
	} else {
		c.JSON(200, gin.H{
			"code":    "SUCCESS",
			"message": "接收成功",
		})
	}
}
